import { CalendarPicker, InfiniteScroll, Picker, Popup } from 'antd-mobile';
import { RightOutline } from 'antd-mobile-icons';
import { FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
import './STCRecord.less';
import InfiniteScrollContent from '@/components/InfiniteScrollContentComponent/InfiniteScrollContentComponent';
import HeaderComponent from '@/components/HeaderComponent/HeaderComponent';
import { MatchEnum, getMatchList } from '@/api/module/STC';

const AssetsComponent: FC<{
  totalBuy: number;
  totalSell: number;
  balance: number;
}> = (props) => {
  const { t } = useTranslation();
  const assetsList: Array<{
    title: string;
    key: keyof typeof props;
    value: number;
  }> = [
    {
      title: 'incomeReceived',
      key: 'totalBuy',
      value: 21,
    },
    {
      title: 'disbursement',
      key: 'totalSell',
      value: 21,
    },
    {
      title: 'total',
      key: 'balance',
      value: 21,
    },
  ];
  return (
    <div className="mt-4">
      <div className="flex items-center justify-between asstest mx-2 bg-bg-1 py-4 px-4 rounded-xl"></div>
      <div className="value text-white-1 py-8 px-5 bg-custom-gradient-1 rounded-xl relative -top-4 flex items-center justify-between">
        {assetsList.map((item) => {
          return (
            <div>
              <div className="opacity-50">{t(item.title)}</div>
              <div className="text-2xl font-semibold">{props[item.key]}</div>
              {/* <div className="text-2xl mt-4">({item.value})</div> */}
            </div>
          );
        })}
      </div>
    </div>
  );
};

const LogsComponent: FC<{
  loadMore: (isRetry: boolean) => Promise<void>;
  hasMore: boolean;
  data: Awaited<ReturnType<typeof getMatchList>>['data']['list_data'];
}> = ({ loadMore, hasMore, data }) => {
  const { t } = useTranslation();
  const param = useParams();
  const [startDate, setStartDate] = useState<[Date, Date] | null>();
  const [visible1, setVisible1] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [pickerVisible, setPickerVisible] = useState(false);
  const typeColumns = [
    [
      { label: '周期 1', value: '1' },
      { label: '周期 2', value: '2' },
      { label: '周期 3', value: '3' },
      { label: '周期 4', value: '4' },
      { label: '周期 5', value: '5' },
    ],
  ];
  const [pickerValue, setPickerValue] = useState<(string | null)[]>();
  const [pickerShowInfo, setPickerShowInfo] = useState<{
    label: string;
    value: string;
  }>();
  const confirmSearch = () => {
    console.log(pickerValue, startDate);
  };
  return (
    <div className="mt-4">
      <div className="flex justify-between items-center">
        <div className="tab flex font-semibold">
          {param.type === 'buy' ? t('buyDetail') : t('sellDetail')}
        </div>

        {/* <div onClick={() => setVisible1(true)} className="text-font-2">
          {t('filter')}
        </div> */}
      </div>
      <div className="logs mt-6 text-sm">
        <div className="text-white-1 bg-bg-1 mb-4 rounded-lg p-4  text-center">
          <div>
            <div className="logs-tab-title flex justify-between items-center ">
              <div className="w-2/5 text-left">{t('date')}</div>
              <div className="w-1/5">{t('type')}</div>
              <div className="w-1/5">{t('price')}</div>
              <div className="w-1/5">{t('amount')}</div>
              <div className="w-1/5">{t('totalValue')}</div>
            </div>
            <div
              className="logs-tab-content overflow-y-scroll"
              style={{
                maxHeight: 'calc(100vh - 380px)',
              }}
            >
              {data.map((item) => (
                <div
                  key={item.create_time}
                  className="flex justify-between items-center py-2"
                >
                  <div className="w-2/5 text-left">{item.create_time}</div>
                  <div className="w-1/5">
                    {param?.type == 'buy'
                      ? item.currency_buy
                      : item.sale_amount}
                  </div>
                  <div className="w-1/5">{item.price}</div>
                  <div className="w-1/5">{item.price}</div>
                  <div className="w-1/5 text-font-2">{item.total_price}</div>
                </div>
              ))}
              <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
                <InfiniteScrollContent hasMore={hasMore} />
              </InfiniteScroll>
            </div>
          </div>
        </div>
      </div>
      <Popup
        visible={visible1}
        position="right"
        onMaskClick={() => {
          setVisible1(false);
        }}
        onClose={() => {
          setVisible1(false);
        }}
        bodyStyle={{ width: '60vw' }}
      >
        <div className="px-4 py-6">
          <div onClick={() => setVisible2(true)} className="date">
            <div className="select-date font-bold text-lg">选择时间</div>
            <div>
              {startDate?.length ? (
                <div>
                  {startDate[0].getFullYear() +
                    '-' +
                    startDate[0].getMonth() +
                    '-' +
                    startDate[0].getDate()}
                  <span className="mx-2">——</span>
                  {startDate[1].getFullYear() +
                    '-' +
                    startDate[1].getMonth() +
                    '-' +
                    startDate[1].getDate()}
                </div>
              ) : (
                '请选择时间'
              )}
            </div>
          </div>
          <div className="type">
            <div className="select-type mt-4 font-bold text-lg">种类</div>
            <div
              onClick={() => setPickerVisible(true)}
              className="flex justify-between items-center"
            >
              <span>
                {!pickerValue?.length ? '请选择种类' : pickerShowInfo?.label}
              </span>
              <RightOutline />
            </div>
          </div>

          <div className="flex justify-between text-center font-bold absolute w-full bottom-0 left-0 py-4 px-4">
            <div
              onClick={() => confirmSearch()}
              className="bg-bg-16 text-white-1 flex-1 rounded-full py-2"
            >
              {t('confirm')}
            </div>
            <div
              onClick={() => {
                setStartDate(null);
                setPickerValue([]);
                setPickerShowInfo({
                  label: '',
                  value: '',
                });
              }}
              className="flex-1  rounded-full py-2 bg-bg-18 ml-4 text-white-1"
            >
              {t('reset')}
            </div>
          </div>
        </div>
      </Popup>
      <CalendarPicker
        visible={visible2}
        selectionMode="range"
        value={startDate}
        max={new Date()}
        min={new Date('2024-12-01')}
        className={`calendar-custom`}
        renderTop={(_) => {
          return <div className="hidden"></div>;
        }}
        onClose={() => setVisible2(false)}
        onMaskClick={() => setVisible2(false)}
        onChange={(val) => {
          console.log(val);
          setStartDate(val);
        }}
      />
      <Picker
        cancelText={t('cancel')}
        confirmText={t('confirm')}
        columns={typeColumns}
        visible={pickerVisible}
        onClose={() => {
          setPickerVisible(false);
        }}
        value={pickerValue}
        onConfirm={(v, extend) => {
          // @ts-ignore
          setPickerValue(v);
          // @ts-ignore
          setPickerShowInfo((val) => {
            return {
              ...val,
              ...extend.items[0],
            };
          });
          console.log(v, extend.items);
        }}
      />
    </div>
  );
};
export default function STCRecord() {
  const { t } = useTranslation();
  const param = useParams<{
    type: keyof typeof title;
  }>();
  console.log(param);
  const [allBuyAmount, setAllBuyAmount] = useState(0);
  const [allSellAmount, setAllSellAmount] = useState(0);
  const [banlance, setBanlance] = useState(0);
  const [page, setPage] = useState(1);
  const [data, setData] = useState<
    Awaited<ReturnType<typeof getMatchList>>['data']['list_data']
  >([]);
  const [hasMore, setHasMore] = useState(true);

  async function loadMore() {
    const res = await getMatchList({
      page: page + '',
      type: param?.type == 'buy' ? MatchEnum.buyer : MatchEnum.seller,
    });
    setAllBuyAmount(res.data.total_buy);
    setAllSellAmount(res.data.total_sell);
    setBanlance(res.data.balnace);
    setPage(page + 1);
    setData((val) => [...val, ...res.data.list_data]);
    setHasMore(res.data.total_page > +res.data.page_on);
  }
  const title = {
    buy: 'STCBuyRecord',
    sell: 'STCSellRecord',
  };

  return (
    <div className="text-white-1 px-4">
      <HeaderComponent
        centerStyle={{
          fontSize: '18px',
        }}
        title={t(param.type ? title[param?.type] : 'STCBuyRecord')}
      />
      <AssetsComponent
        totalBuy={allBuyAmount}
        totalSell={allSellAmount}
        balance={banlance}
      />
      <LogsComponent loadMore={loadMore} hasMore={hasMore} data={data} />
    </div>
  );
}
